package com.dnd.monitor.service;

import com.dnd.monitor.common.enums.AreaEnum;
import com.dnd.monitor.entity.DocumentNumberCalc;
import com.dnd.monitor.mapper.MonitorMapper;
import com.dnd.monitor.strategy.context.StrategyContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 安贺
 * @CreateTime 2022年08月09日 16:39:00
 * @Description: 开始执行类
 */
@Service
@Slf4j
public class ExecuteService {

    @Autowired
    private MonitorMapper monitorMapper;

    @Autowired
    private StrategyContext strategyContext;

    /**
     * 执行
     */
    public void execute() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
        //查询本地库的文书号列表
        List<DocumentNumberCalc> allDocumentNumberCalcs = monitorMapper.selectList();
        if (allDocumentNumberCalcs.isEmpty()) {
            log.info("本地库未发现可执行的数据");
            return;
        }
        //根据areaName分组
        Map<String, List<DocumentNumberCalc>> areaNameMaps = allDocumentNumberCalcs.stream()
                .collect(Collectors.groupingBy(DocumentNumberCalc::getAreaName, Collectors.toList()));
        List<String> areas = new ArrayList<>(areaNameMaps.keySet());
        log.info("可执行的地区有：{}",areas);
        for (Map.Entry<String, List<DocumentNumberCalc>> stringListEntry : areaNameMaps.entrySet()) {
            AreaEnum areaEnum = AreaEnum.getAreaEnum(stringListEntry.getKey());
            //会根据当前地区，去找相应执行策略模板进行执行
            strategyContext.executeStrategy(stringListEntry.getValue(), areaEnum);
        }
        log.info("执行完毕！");
    }

}
